<template>
  <div class="terminal-container">
    <el-card class="terminal-card">
      <template #header>
        <div class="terminal-header">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-icon :size="20" style="color: var(--cyber-primary)"><Monitor /></el-icon>
            <span class="terminal-title">SSH终端 - {{ hostInfo.hostname }}</span>
            <el-tag v-if="connected" type="success" size="small">已连接</el-tag>
            <el-tag v-else type="info" size="small">未连接</el-tag>
          </div>
          <div>
            <el-button 
              v-if="!connected" 
              type="primary" 
              size="small" 
              @click="connect"
              :loading="connecting"
            >
              连接
            </el-button>
            <el-button 
              v-else 
              type="danger" 
              size="small" 
              @click="disconnect"
            >
              断开
            </el-button>
            <el-button size="small" @click="clearTerminal">
              清屏
            </el-button>
            <el-button size="small" @click="$router.back()">
              返回
            </el-button>
          </div>
        </div>
      </template>
      <div ref="terminalRef" class="terminal-wrapper"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'
import { hostAPI } from '@/api'
import { ElMessage } from 'element-plus'

const route = useRoute()
const terminalRef = ref(null)
let terminal = null
let fitAddon = null
let socket = null

const hostId = ref(route.params.id)
const hostInfo = ref({})
const connected = ref(false)
const connecting = ref(false)

// 加载主机信息
const loadHostInfo = async () => {
  try {
    const res = await hostAPI.getDetail(hostId.value)
    hostInfo.value = res
  } catch (error) {
    ElMessage.error('加载主机信息失败')
  }
}

// 初始化终端
const initTerminal = () => {
  terminal = new Terminal({
    cursorBlink: true,
    cursorStyle: 'block',
    fontSize: 14,
    fontFamily: 'Courier New, monospace',
    theme: {
      background: '#0a0e27',
      foreground: '#00ff9f',
      cursor: '#00ff9f',
      cursorAccent: '#0a0e27',
      black: '#0a0e27',
      red: '#ff006e',
      green: '#00ff9f',
      yellow: '#ffbe0b',
      blue: '#00d4ff',
      magenta: '#ff006e',
      cyan: '#00d4ff',
      white: '#e0e0e0',
      brightBlack: '#8892b0',
      brightRed: '#ff4d6d',
      brightGreen: '#5fff8f',
      brightYellow: '#ffd60a',
      brightBlue: '#5fe4ff',
      brightMagenta: '#ff4d9d',
      brightCyan: '#5fe4ff',
      brightWhite: '#ffffff'
    },
    rows: 30,
    cols: 100
  })

  fitAddon = new FitAddon()
  terminal.loadAddon(fitAddon)
  terminal.open(terminalRef.value)
  fitAddon.fit()

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    fitAddon.fit()
    if (socket && socket.readyState === WebSocket.OPEN) {
      const dimensions = fitAddon.proposeDimensions()
      socket.send(JSON.stringify({
        action: 'resize',
        cols: dimensions.cols,
        rows: dimensions.rows
      }))
    }
  })

  // 监听用户输入
  terminal.onData((data) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify({
        action: 'input',
        data: data
      }))
    }
  })

  terminal.writeln('\x1b[1;32m欢迎使用CMDB SSH终端\x1b[0m')
  terminal.writeln('\x1b[1;36m点击"连接"按钮开始SSH连接...\x1b[0m')
  terminal.writeln('')
}

// 连接SSH
const connect = () => {
  connecting.value = true
  
  // 构建WebSocket URL
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const wsUrl = `${protocol}//${window.location.hostname}:8000/ws/ssh/`
  
  socket = new WebSocket(wsUrl)

  socket.onopen = () => {
    terminal.writeln('\x1b[1;32m正在连接到主机...\x1b[0m')
    
    // 发送连接请求
    socket.send(JSON.stringify({
      action: 'connect',
      host_id: hostId.value
    }))
  }

  socket.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      
      if (data.status === 'connected') {
        connected.value = true
        connecting.value = false
        terminal.writeln('\x1b[1;32m' + data.message + '\x1b[0m')
        terminal.writeln('')
        ElMessage.success('连接成功')
      } else if (data.output) {
        terminal.write(data.output)
      } else if (data.error) {
        terminal.writeln('\x1b[1;31m错误: ' + data.error + '\x1b[0m')
        ElMessage.error('SSH错误: ' + data.error)
        connecting.value = false
      }
    } catch (error) {
      console.error('处理消息失败:', error)
    }
  }

  socket.onerror = (error) => {
    console.error('WebSocket错误:', error)
    terminal.writeln('\x1b[1;31mWebSocket连接错误\x1b[0m')
    ElMessage.error('连接错误')
    connecting.value = false
  }

  socket.onclose = () => {
    connected.value = false
    connecting.value = false
    terminal.writeln('\x1b[1;33m连接已断开\x1b[0m')
  }
}

// 断开连接
const disconnect = () => {
  if (socket) {
    socket.close()
    socket = null
  }
  connected.value = false
  terminal.writeln('\x1b[1;33m已断开连接\x1b[0m')
}

// 清屏
const clearTerminal = () => {
  if (terminal) {
    terminal.clear()
  }
}

onMounted(async () => {
  await loadHostInfo()
  initTerminal()
})

onUnmounted(() => {
  if (socket) {
    socket.close()
  }
  if (terminal) {
    terminal.dispose()
  }
})
</script>

<style scoped>
.terminal-container {
  padding: 20px;
  height: calc(100vh - 100px);
}

.terminal-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.terminal-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.terminal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.terminal-title {
  font-size: 16px;
  font-weight: bold;
  color: var(--cyber-primary);
  font-family: 'Courier New', monospace;
}

.terminal-wrapper {
  height: 100%;
  padding: 10px;
  background: #0a0e27;
  border: 2px solid var(--cyber-primary);
  border-radius: 4px;
  box-shadow: 0 0 20px rgba(0, 255, 159, 0.3);
}

.terminal-wrapper :deep(.xterm) {
  height: 100%;
}

.terminal-wrapper :deep(.xterm-viewport) {
  overflow-y: auto !important;
}
</style>
